﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using CustomersSuppliersBusinessLayer;
using CustomersSuppliersDataLayer;
using System.Collections;
using WebHelper.Helpers;

namespace CustomersSuppliersWebApplication
{
    public partial class WebFormWorkers : WebFormBase
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                InitializeTelerikRequest(this.RadTextBoxSearch, "onkeyup");
                this.PageTitle = "العاملين";
                this.getJobFilter();
                this.getMaritalStatusFilter();
            }
        }
        protected void RadTextBoxSearch_TextChanged(object sender, EventArgs e)
        {
            this.getWorkers();
            this.RadGridResults.Rebind();
        }
        protected void RadComboBox_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            this.getWorkers();
            this.RadGridResults.Rebind();
        }
        protected void RadDatePicker_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {
            this.getWorkers();
            this.RadGridResults.Rebind();
        }
        protected void RadGridResults_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            this.getWorkers();
        }
        protected void RadGridResults_ItemCreated(object sender, GridItemEventArgs e)
        {
            //pager
            if (e.Item is GridPagerItem)
            {
                GridPagerItem item = e.Item as GridPagerItem;
                Button changePageSize = (Button)e.Item.FindControl("ChangePageSizeLinkButton");
                changePageSize.Text = "تغيير";
                Button goTO = (Button)e.Item.FindControl("GoToPageLinkButton");
                goTO.Text = "تغيير";
                Label itesNumberLabel = (Label)e.Item.FindControl("ChangePageSizeLabel");
                itesNumberLabel.Text = "          عدد الصفوف :";
                Label goTOLabel = (Label)e.Item.FindControl("GoToPageLabel");
                goTOLabel.Text = "صفحة :";
                Label ofLabel = (Label)e.Item.FindControl("PageOfLabel");
                ofLabel.Text = "من " + item.Paging.PageCount.ToString();
            }
        }
        protected void RadGridResults_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Attachments")
            {
                this.ShowWindow("WebFormWorkersAttachments.aspx?" + BLWorker.PropertiesNames.Worker_ID + "=" + e.CommandArgument);
            }

            //set default value
            if (e.CommandName == RadGrid.InitInsertCommandName)
            {
                e.Canceled = true;
                System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();
                newValues[BLWorker.PropertiesNames.Worker_ResidenceDate] = DateTime.Now.Date;
                e.Item.OwnerTableView.InsertItem(newValues);
            }

        }
        protected void RadGridResults_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            Hashtable newValues = new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            BLWorker Worker = new BLWorker();
            if (newValues[BLWorker.PropertiesNames.Worker_Code] != null)
            {
                Worker.Worker_Code = newValues[BLWorker.PropertiesNames.Worker_Code].ToString();
            }
            if (newValues[BLWorker.PropertiesNames.Worker_NameAr] != null && newValues[BLWorker.PropertiesNames.Worker_NameAr].ToString().Trim() != "")
            {
                Worker.Worker_NameAr = newValues[BLWorker.PropertiesNames.Worker_NameAr].ToString();
            }
            else
            {
                this.ShowNotification("من فضلك قم بادخال الاسم", NotificationIconType.Warning);
                e.Canceled = true;
                return;
            }
            if (newValues[BLWorker.PropertiesNames.Worker_NameEn] != null)
            {
                Worker.Worker_NameEn = newValues[BLWorker.PropertiesNames.Worker_NameEn].ToString();
            }
            RadComboBox radComboBoxJob = (RadComboBox)editedItem.FindControl("RadComboBoxJob");
            if (radComboBoxJob.SelectedValue != "")
            {
                Worker.Job_ID = new Guid(radComboBoxJob.SelectedValue);
            }
            if (newValues[BLWorker.PropertiesNames.Worker_ResidenceNumber] != null)
            {
                Worker.Worker_ResidenceNumber = Convert.ToDecimal(newValues[BLWorker.PropertiesNames.Worker_ResidenceNumber]);
            }
            if (Convert.ToDateTime(newValues[BLWorker.PropertiesNames.Worker_ResidenceDate]).Year > 1900)
            {
                Worker.Worker_ResidenceDate = Convert.ToDateTime(newValues[BLWorker.PropertiesNames.Worker_ResidenceDate]);
            }
            if (newValues[BLWorker.PropertiesNames.Worker_Notes] != null)
            {
                Worker.Worker_Notes = newValues[BLWorker.PropertiesNames.Worker_Notes].ToString();
            }
            RadComboBox radComboBoxMaritalStatus = (RadComboBox)editedItem.FindControl("RadComboBoxMaritalStatus");
            if (radComboBoxMaritalStatus.SelectedValue != "")
            {
                Worker.MaritalStatus_ID = new Guid(radComboBoxMaritalStatus.SelectedValue);
            }
            RadButton RadButtonHaveFamily = (RadButton)editedItem.FindControl("RadButtonHaveFamily");
            Worker.HaveFamily = RadButtonHaveFamily.Checked ? (byte)1 : (byte)0;

            RadButton RadButtonHaveHaveExternalGuaranty = (RadButton)editedItem.FindControl("RadButtonHaveHaveExternalGuaranty");
            Worker.HaveExternalGuaranty = RadButtonHaveHaveExternalGuaranty.Checked ? (byte)1 : (byte)0;

            Worker.Worker_Search = StringHelper.ToUniqueStatement(Worker.Worker_Code + Worker.Worker_NameAr + Worker.Worker_NameEn + Worker.Worker_Notes);
            Worker.AutoSave();
            if (Worker.Error == null)
            {
                this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void RadGridResults_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            Hashtable newValues = new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            BLWorker Worker = new BLWorker();
            Worker.Worker_ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLWorker.PropertiesNames.Worker_ID].ToString());
            Worker.LoadByIdentifiers();

            if (newValues[BLWorker.PropertiesNames.Worker_Code] != null)
            {
                Worker.Worker_Code = newValues[BLWorker.PropertiesNames.Worker_Code].ToString();
            }
            if (newValues[BLWorker.PropertiesNames.Worker_NameAr] != null && newValues[BLWorker.PropertiesNames.Worker_NameAr].ToString().Trim() != "")
            {
                Worker.Worker_NameAr = newValues[BLWorker.PropertiesNames.Worker_NameAr].ToString();
            }
            else
            {
                this.ShowNotification("من فضلك قم بادخال الاسم", NotificationIconType.Warning);
                e.Canceled = true;
                return;
            }
            if (newValues[BLWorker.PropertiesNames.Worker_NameEn] != null)
            {
                Worker.Worker_NameEn = newValues[BLWorker.PropertiesNames.Worker_NameEn].ToString();
            }
            RadComboBox radComboBoxJob = (RadComboBox)editedItem.FindControl("RadComboBoxJob");
            if (radComboBoxJob.SelectedValue != "")
            {
                Worker.Job_ID = new Guid(radComboBoxJob.SelectedValue);
            }
            if (newValues[BLWorker.PropertiesNames.Worker_ResidenceNumber] != null)
            {
                Worker.Worker_ResidenceNumber = Convert.ToDecimal(newValues[BLWorker.PropertiesNames.Worker_ResidenceNumber]);
            }
            if (Convert.ToDateTime(newValues[BLWorker.PropertiesNames.Worker_ResidenceDate]).Year > 1900)
            {
                Worker.Worker_ResidenceDate = Convert.ToDateTime(newValues[BLWorker.PropertiesNames.Worker_ResidenceDate]);
            }
            if (newValues[BLWorker.PropertiesNames.Worker_Notes] != null)
            {
                Worker.Worker_Notes = newValues[BLWorker.PropertiesNames.Worker_Notes].ToString();
            }
            RadComboBox radComboBoxMaritalStatus = (RadComboBox)editedItem.FindControl("RadComboBoxMaritalStatus");
            if (radComboBoxMaritalStatus.SelectedValue != "")
            {
                Worker.MaritalStatus_ID = new Guid(radComboBoxMaritalStatus.SelectedValue);
            }
            RadButton RadButtonHaveFamily = (RadButton)editedItem.FindControl("RadButtonHaveFamily");
            Worker.HaveFamily = RadButtonHaveFamily.Checked ? (byte)1 : (byte)0;

            RadButton RadButtonHaveHaveExternalGuaranty = (RadButton)editedItem.FindControl("RadButtonHaveHaveExternalGuaranty");
            Worker.HaveExternalGuaranty = RadButtonHaveHaveExternalGuaranty.Checked ? (byte)1 : (byte)0;

            Worker.Worker_Search = StringHelper.ToUniqueStatement(Worker.Worker_Code + Worker.Worker_NameAr + Worker.Worker_NameEn + Worker.Worker_Notes);
            Worker.AutoSave();
            if (Worker.Error == null)
            {
                this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void RadGridResults_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            BLWorker Worker = new BLWorker();
            Worker.Worker_ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLWorker.PropertiesNames.Worker_ID].ToString());
            Worker.DeleteByIdentifiers();
            if (Worker.Error == null)
            {
                this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحذف", NotificationIconType.Error);
                return;
            }
        }
        protected void RadGridResults_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                BLWorker Worker = (BLWorker)e.Item.DataItem;
                
                RadButton RadButtonHaveFamilyDisplay = (RadButton)e.Item.FindControl("RadButtonHaveFamilyDisplay");
                RadButtonHaveFamilyDisplay.Checked = Worker.HaveFamily == 1;
                
                RadButton RadButtonHaveHaveExternalGuarantyDisplay = (RadButton)e.Item.FindControl("RadButtonHaveHaveExternalGuarantyDisplay");
                RadButtonHaveHaveExternalGuarantyDisplay.Checked = Worker.HaveExternalGuaranty == 1;
            }

            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                //combobox Job
                RadComboBox radComboBoxJob = (RadComboBox)e.Item.FindControl("RadComboBoxJob");
                radComboBoxJob.DataSource = CashVariables.JobCollection;
                radComboBoxJob.DataTextField = BLJob.PropertiesNames.Job_NameAr;
                radComboBoxJob.DataValueField = BLJob.PropertiesNames.Job_ID;
                radComboBoxJob.DataBind();
                if (e.Item.ItemIndex != -1)
                {
                    BLWorker Worker = (BLWorker)e.Item.DataItem;
                    radComboBoxJob.SelectedValue = Worker.Job_ID.ToString();
                }
                //combobox MaritalStatus
                RadComboBox radComboBoxMaritalStatus = (RadComboBox)e.Item.FindControl("RadComboBoxMaritalStatus");
                radComboBoxMaritalStatus.DataSource = CashVariables.MaritalStatuCollection;
                radComboBoxMaritalStatus.DataTextField = BLMaritalStatu.PropertiesNames.MaritalStatus_NameAr;
                radComboBoxMaritalStatus.DataValueField = BLMaritalStatu.PropertiesNames.MaritalStatus_ID;
                radComboBoxMaritalStatus.DataBind();
                if (e.Item.ItemIndex != -1)
                {
                    BLWorker Worker = (BLWorker)e.Item.DataItem;
                    radComboBoxMaritalStatus.SelectedValue = Worker.MaritalStatus_ID.ToString();
                }

                //check box have family
                RadButton RadButtonHaveFamily = (RadButton)e.Item.FindControl("RadButtonHaveFamily");
                if (e.Item.ItemIndex != -1)
                {
                    BLWorker Worker = (BLWorker)e.Item.DataItem;
                    RadButtonHaveFamily.Checked = Worker.HaveFamily == 1;
                }

                //check box have external gurantee
                RadButton RadButtonHaveHaveExternalGuaranty = (RadButton)e.Item.FindControl("RadButtonHaveHaveExternalGuaranty");
                if (e.Item.ItemIndex != -1)
                {
                    BLWorker Worker = (BLWorker)e.Item.DataItem;
                    RadButtonHaveHaveExternalGuaranty.Checked = Worker.HaveExternalGuaranty == 1;
                }

                
                //width
                GridEditableItem editedItem = e.Item as GridEditableItem;
                GridEditManager editMan = editedItem.EditManager;
                GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)(editMan.GetColumnEditor(BLWorker.PropertiesNames.Worker_Notes));
                editor.TextBoxMode = TextBoxMode.MultiLine;
                editor.TextBoxControl.Width = Unit.Pixel(300);
                editor.TextBoxControl.Height = Unit.Pixel(40);
            }
        }

        private void getWorkers()
        {
            BLWorkerCollection WorkerCollection = new BLWorkerCollection();
            //sort
            WorkerCollection.Template.AddSort(BLWorker.PropertiesNames.Worker_RowNumber, false);
            
            //search filter
            WorkerCollection.Template.AddFilter(LogicalOperators.And, BLWorker.PropertiesNames.Worker_Search, FilterOperators.Contains, this.RadTextBoxSearch.Text, typeof(string));
            
            //Job filter
            if (this.RadComboBoxJob.SelectedValue == "11111111-1111-1111-1111-111111111111")
            {

            }
            else if (this.RadComboBoxJob.SelectedValue == "00000000-0000-0000-0000-000000000000")
            {
                WorkerCollection.Template.AddFilter(LogicalOperators.And, BLWorker.PropertiesNames.Job_ID, FilterOperators.Undefined, null, typeof(Guid));
            }
            else
            {
                WorkerCollection.Template.AddFilter(LogicalOperators.And, BLWorker.PropertiesNames.Job_ID, FilterOperators.Equal, new Guid(this.RadComboBoxJob.SelectedValue), typeof(Guid));
            }

            //MaritalStatus filter
            if (this.RadComboBoxMaritalStatus.SelectedValue == "11111111-1111-1111-1111-111111111111")
            {

            }
            else if (this.RadComboBoxMaritalStatus.SelectedValue == "00000000-0000-0000-0000-000000000000")
            {
                WorkerCollection.Template.AddFilter(LogicalOperators.And, BLWorker.PropertiesNames.MaritalStatus_ID, FilterOperators.Undefined, null, typeof(Guid));
            }
            else
            {
                WorkerCollection.Template.AddFilter(LogicalOperators.And, BLWorker.PropertiesNames.MaritalStatus_ID, FilterOperators.Equal, new Guid(this.RadComboBoxMaritalStatus.SelectedValue), typeof(Guid));
            }

            //dateFrom filter
            if (this.RadDatePickerFrom.SelectedDate != null)
            {
                WorkerCollection.Template.AddFilter(LogicalOperators.And, BLWorker.PropertiesNames.Worker_ResidenceDate, FilterOperators.GreaterThanOrEqual, this.RadDatePickerFrom.SelectedDate, typeof(DateTime));
            }

            //dateTo filter
            if (this.RadDatePickerTo.SelectedDate != null)
            {
                WorkerCollection.Template.AddFilter(LogicalOperators.And, BLWorker.PropertiesNames.Worker_ResidenceDate, FilterOperators.LessThanOrEqual, this.RadDatePickerTo.SelectedDate, typeof(DateTime));
            }
            
            //load
            WorkerCollection.Load();


            for (int i = 0; i < WorkerCollection.Count; i++)
            {
                int index = CashVariables.JobCollection.FindByIentifier(WorkerCollection[i].Job_ID);
                if (index != -1)
                {
                    WorkerCollection[i].Job_NameAr = CashVariables.JobCollection[index].Job_NameAr;
                }
                index = CashVariables.MaritalStatuCollection.FindByIentifier(WorkerCollection[i].MaritalStatus_ID);
                if (index != -1)
                {
                    WorkerCollection[i].MaritalStatus_NameAr = CashVariables.MaritalStatuCollection[index].MaritalStatus_NameAr;
                }
            }
            
            if (WorkerCollection.Error != null)
            {
                this.ShowNotification("حدث خطا اثناء استعراض البيانات", NotificationIconType.Error);
            }
            this.RadGridResults.DataSource = WorkerCollection;
            this.RadGridResults.MasterTableView.DataKeyNames = BLWorker.PropertiesNames.Identifiers;
        }
        private void getJobFilter()
        {
            BLJobCollection JobCollection = new BLJobCollection(CashVariables.JobCollection);
            JobCollection.Insert(0, new BLJob { Job_ID = new Guid("00000000-0000-0000-0000-000000000000"), Job_NameAr = "بدون" });
            JobCollection.Insert(0, new BLJob { Job_ID = new Guid("11111111-1111-1111-1111-111111111111"), Job_NameAr = "الكل" });
            this.RadComboBoxJob.DataSource = JobCollection;
            this.RadComboBoxJob.DataTextField = BLJob.PropertiesNames.Job_NameAr;
            this.RadComboBoxJob.DataValueField = BLJob.PropertiesNames.Job_ID;
            this.RadComboBoxJob.DataBind();
        }
        private void getMaritalStatusFilter()
        {
            BLMaritalStatuCollection MaritalStatusCollection = new BLMaritalStatuCollection(CashVariables.MaritalStatuCollection);
            MaritalStatusCollection.Insert(0, new BLMaritalStatu { MaritalStatus_ID = new Guid("00000000-0000-0000-0000-000000000000"), MaritalStatus_NameAr = "بدون" });
            MaritalStatusCollection.Insert(0, new BLMaritalStatu { MaritalStatus_ID = new Guid("11111111-1111-1111-1111-111111111111"), MaritalStatus_NameAr = "الكل" });
            this.RadComboBoxMaritalStatus.DataSource = MaritalStatusCollection;
            this.RadComboBoxMaritalStatus.DataTextField = BLMaritalStatu.PropertiesNames.MaritalStatus_NameAr;
            this.RadComboBoxMaritalStatus.DataValueField = BLMaritalStatu.PropertiesNames.MaritalStatus_ID;
            this.RadComboBoxMaritalStatus.DataBind();
        }
    }
}